﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml;


namespace OCSMgmt
{
    public partial class OcsManager : Form
    {
        public OcsManager()
        {
            InitializeComponent();

        }
        UsersCollection AllOcsUsers = MOC.GetUsers();
        UsersCollection SelectedUsers = new UsersCollection();
        private void button1_Click(object sender, EventArgs e)
        {
            SaveFileDialog SaveFile = new SaveFileDialog();
            SaveFile.AddExtension = true;
            SaveFile.DefaultExt = ".xml";
            SaveFile.CheckFileExists = false;
            SaveFile.OverwritePrompt = true;
            SaveFile.FileName = "Template1";
            SaveFile.Filter = "Xml Template File (*.xml)|*.xml|All files (*.*)|*.*";
            if (SaveFile.ShowDialog() == DialogResult.OK)
            {
                XmlTextWriter TextWriter = new XmlTextWriter(SaveFile.FileName, Encoding.ASCII);
                TextWriter.WriteStartDocument();
                TextWriter.WriteStartElement("Contacts");
                TextWriter.WriteAttributeString("UserInstanceID", ((Group)GroupsTV.Nodes[0].Tag).UserInstanceID);
                SaveNodes(GroupsTV.Nodes, TextWriter);
                TextWriter.WriteEndElement();
                TextWriter.Close();
            }
        }
        private void UpdateDataGrid()
        {

            AllOcsUsersDGV.DataSource = AllOcsUsers;
            int width = AllOcsUsersDGV.Width / AllOcsUsersDGV.ColumnCount;
            AllOcsUsersDGV.Columns[AllOcsUsersDGV.ColumnCount - 1].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
            AllOcsUserCountLBL.Text = "OCS Available Users : " + AllOcsUsersDGV.Rows.Count.ToString();
            for (int i = 0; i < AllOcsUsersDGV.ColumnCount; i++)
            {
                AllOcsUsersDGV.Columns[i].Width = width;
            }
            SelectedUsersCountLBL.Text = "Selected Users : "+SelectedUsersDGV.Rows.Count.ToString();
            AllOcsUsersDGV.Refresh();
            SelectedUsersDGV.Refresh();
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OcsManager_Load(object sender, EventArgs e)
        {
            //Get users from Server
            ToolTip CollapseTT = new ToolTip();
            ToolTip ExpandTT = new ToolTip();
            ToolTip DonateTT = new ToolTip();
            DonateTT.IsBalloon=true;
            DonateTT.ReshowDelay = 0;
            DonateTT.UseAnimation = true;
            CollapseTT.IsBalloon =ExpandTT.IsBalloon = false;
            CollapseTT.UseFading=ExpandTT.UseFading=DonateTT.UseFading=true;
            CollapseTT.SetToolTip(CollapsePBox, "Collapse All");
            ExpandTT.SetToolTip(ExpandPBox, "Expand All");
            DonateTT.SetToolTip(DonateLinkLabel, "If you like it\noffer me a beer..!!");
            ExportAsTemplateBTN.Enabled = false;
            AllOcsUsersDGV.DataSource = AllOcsUsers;
            SelectedUsersDGV.DataSource = SelectedUsers;
            SelectedUsersDGV.Columns[1].Visible = false;
            SelectedUsersDGV.Columns[0].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
            SelectedUsersCountLBL.Text = "Selected Users : " + SelectedUsersDGV.Rows.Count.ToString();
            UpdateDataGrid();
        }

        private void SelectOneBTN_Click(object sender, EventArgs e)
        {
            if (AllOcsUsersDGV.Rows.Count > 0)
            {
                User u = AllOcsUsersDGV.SelectedRows[0].DataBoundItem as User;
                SelectUser(u);
                UpdateDataGrid();
            }
        }

        private void SelectAllBTN_Click(object sender, EventArgs e)
        {
            if (AllOcsUsersDGV.Rows.Count > 0)
            {
                foreach (DataGridViewRow r in AllOcsUsersDGV.Rows)
                {
                    User u = r.DataBoundItem as User;
                    SelectUser(u);
                }
                UpdateDataGrid();
            }
        }

        private void UnSelectOneBTN_Click(object sender, EventArgs e)
        {
            if ( SelectedUsersDGV.Rows.Count > 0)
            {
                User u = SelectedUsersDGV.SelectedRows[0].DataBoundItem as User;
                UnSelectUser(u);
                UpdateDataGrid();
            }
        }

        private void UnSelectAllBTN_Click(object sender, EventArgs e)
        {
            SelectedUsers.Clear();
            UpdateDataGrid();
        }

        private void SelectUser(User User)
        {
            if (User != null)
            {
                int result = SelectedUsers.IndexOf(User);
                if (result == -1)
                {
                    SelectedUsers.Add(User);
                }
            }
            
        }

        private void UnSelectUser(User User)
        {
            if (User != null)
            {
                int result = SelectedUsers.IndexOf(User);
                if (result != -1)
                {
                    SelectedUsers.Remove(User);
                }
            }

        }

        private void SelectedUsersDGV_CellMouseUp(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right && SelectedUsersDGV.Rows.Count>0) 
            {
                SelectedUsersDGV.Rows[e.RowIndex].Selected = true;
                SelectedUsersDGV_CTX_Menu.Show(SelectedUsersDGV, SelectedUsersDGV.PointToClient(Cursor.Position));
            }
        }

        private void wipeContactListToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //DataGridView dgv = sender as DataGridView;
            User u = SelectedUsersDGV.SelectedRows[0].DataBoundItem as User;
            if (MessageBox.Show("WARNING: You are wiping contact list to user " + u.DisplayName + "\n\t\tARE YOU SURE?",
                            "Contact List WIPE",
                            MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
            {
                Cursor SaveCursor = Cursor.Current;
                Cursor.Current = Cursors.WaitCursor;
                MOC.DeleteContact(u.InstanceID,"");
                MOC.DeleteGroups(u.InstanceID, "");
                Cursor.Current = SaveCursor;
            }
            GroupsTV.Nodes.Clear();
            if (SelectedUsersDGV.Rows.Count > 0)
            {
                LoadGroupsAndContactsFromServer();
            }
              
        }

        private void SelectedUsersDGV_SelectionChanged(object sender, EventArgs e)
        {

            GroupsTV.Nodes.Clear();
            if (SelectedUsersDGV.Rows.Count > 0) 
            { 
                LoadGroupsAndContactsFromServer();
            }
        }

        private void LoadContactsFromServerToolStripMenuItem_Click(object sender, EventArgs e)
        {
            LoadGroupsAndContactsFromServer();
            
        }
        
        private void LoadGroupsAndContactsFromServer()
        {
            Cursor SaveCursor = Cursor.Current;
            Cursor.Current = Cursors.WaitCursor;

            // Fill Treeview with Contact Groups for this user
            User u = SelectedUsersDGV.SelectedRows[0].DataBoundItem as User;
            GroupsCollection gc = MOC.GetGroupsForUser(u.InstanceID);
            GroupsTV.ImageList = GroupTVIcons;
            GroupsTV.BeginUpdate();
            GroupsTV.Nodes.Clear();
            foreach (Group g in gc)
            {
                TreeNode n = GroupsTV.Nodes.Add(g.Name, g.Name);
                n.ImageIndex = 0;
                n.SelectedImageIndex = 0;
                n.Tag = g;
            }
            GroupsTV.EndUpdate();
            GroupsLBL.Text = "Contacts for : "+ u.DisplayName;

            // Fill Treeview with Contacts in each Groups for this user
            foreach (Group g in gc)
            {
                UsersCollection uc = MOC.GetGroupMembers(u.InstanceID, Convert.ToUInt32(g.GroupID));
                foreach (User usr in uc)
                {
                    int i = AllOcsUsers.IndexOf(usr);
                    if (i != -1)
                    {
                        foreach (TreeNode tn in GroupsTV.Nodes.Find(g.Name, false))
                        {
                            TreeNode n = new TreeNode(AllOcsUsers[i].DisplayName);
                            n.Tag = usr;
                            n.ImageIndex = 1;
                            n.SelectedImageIndex=1;
                            
                            tn.Nodes.Add(n);
                        }

                    }
                }

            }
            Cursor.Current = SaveCursor;
            if (GroupsTV.Nodes.Count > 0)
            {
                ExportAsTemplateBTN.Enabled = true;
            }
            else 
            {
                ExportAsTemplateBTN.Enabled = false;
            }
        }

        private void SaveNodes(TreeNodeCollection nodesCollection, XmlTextWriter textWriter)
        {
            for (int i = 0; i < nodesCollection.Count; i++)
            {
                TreeNode node = nodesCollection[i];
                textWriter.WriteStartElement(node.Level==0?"Group":"User");
                if (node.Level == 0)
                {
                    textWriter.WriteAttributeString("Name",node.Text);
                    textWriter.WriteAttributeString("GroupID", ((Group)node.Tag).GroupID);
                    //textWriter.WriteAttributeString("UserInstanceID", ((Group)node.Tag).UserInstanceID);
                }
                else
                {
                    textWriter.WriteAttributeString("DisplayName", node.Text);
                    textWriter.WriteAttributeString("PrimaryURI", ((User)node.Tag).PrimaryURI.ToLower());
                }
                // add other node properties to serialize here  
                if (node.Nodes.Count > 0)
                {
                    SaveNodes(node.Nodes, textWriter);
                }
                textWriter.WriteEndElement();
            }
        }

        private void createGroupToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string gn = "New Group";
            if (InputBox("New Group", "Enter the new group name:", ref gn) == DialogResult.OK)
            {
                User u = SelectedUsersDGV.SelectedRows[0].DataBoundItem as User;
                try
                {
                    MOC.CreateGroup(u.InstanceID, gn);
                }
                catch(Exception ex) 
                {
                    MessageBox.Show(null,ex.Message,"Create Group",MessageBoxButtons.OK,MessageBoxIcon.Hand);
                }
            }
        }

        private static DialogResult InputBox(string title, string promptText, ref string value)
        {
            Form form = new Form();
            Label label = new Label();
            TextBox textBox = new TextBox();
            Button buttonOk = new Button();
            Button buttonCancel = new Button();

            form.Text = title;
            label.Text = promptText;
            textBox.Text = value;

            buttonOk.Text = "OK";
            buttonCancel.Text = "Cancel";
            buttonOk.DialogResult = DialogResult.OK;
            buttonCancel.DialogResult = DialogResult.Cancel;

            label.SetBounds(9, 20, 372, 13);
            textBox.SetBounds(12, 36, 372, 20);
            buttonOk.SetBounds(228, 72, 75, 23);
            buttonCancel.SetBounds(309, 72, 75, 23);

            label.AutoSize = true;
            textBox.Anchor = textBox.Anchor | AnchorStyles.Right;
            buttonOk.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
            buttonCancel.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;

            form.ClientSize = new Size(396, 107);
            form.Controls.AddRange(new Control[] { label, textBox, buttonOk, buttonCancel });
            form.ClientSize = new Size(Math.Max(300, label.Right + 10), form.ClientSize.Height);
            form.FormBorderStyle = FormBorderStyle.FixedDialog;
            form.StartPosition = FormStartPosition.CenterScreen;
            form.MinimizeBox = false;
            form.MaximizeBox = false;
            form.AcceptButton = buttonOk;
            form.CancelButton = buttonCancel;

            DialogResult dialogResult = form.ShowDialog();
            value = textBox.Text;
            return dialogResult;
        }

        private void deleteContactToolStripMenuItem_Click(object sender, EventArgs e)
        {
            User u = SelectedUsersDGV.SelectedRows[0].DataBoundItem as User;
            User r = GroupsTV.SelectedNode.Tag as User;
            if (MessageBox.Show("Do you really want to delete contact " + r.PrimaryURI + " from " + u.DisplayName + " contacts?",
                            "Contact Deletion",
                            MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) 
            {
                MOC.DeleteContact(u.InstanceID, r.PrimaryURI);
                UpdateGroupsDGV(Cursor.Current);
            }
                          
            
        }
        
        private void testToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }

        private static void ReadNodes(XmlNode xnod ,String InstanceID) 
        { 
            if (xnod.HasChildNodes) 
            {
                xnod = xnod.FirstChild;
                while(xnod != null)
                {
                    if (xnod.Name == "Group")
                    {
                        try
                        {
                            MOC.CreateGroup(InstanceID, xnod.Attributes["Name"].Value.ToString());
                        }
                        catch { }
                    }
                    if (xnod.Name == "User")
                    {
                        MOC.AddContact(InstanceID, xnod.Attributes["PrimaryURI"].Value.ToString(), xnod.ParentNode.Attributes["Name"].Value.ToString());
                    }
                    ReadNodes(xnod,InstanceID);
                    xnod= xnod.NextSibling;
                }
            }
        }

        private void AllOcsUsersDGV_DragDrop(object sender, DragEventArgs e)
        {
            e.Effect = DragDropEffects.None;
        }

        private void GroupsTV_DragDrop(object sender, DragEventArgs e)
        {
            string s = (String)e.Data.GetData(DataFormats.StringFormat);
            Point p = GroupsTV.PointToClient(Cursor.Position);
            TreeNode node=GroupsTV.GetNodeAt(p);
            User user = SelectedUsersDGV.SelectedRows[0].DataBoundItem as User;
            User UserToAdd = AllOcsUsersDGV.SelectedRows[0].DataBoundItem as User;
            Group group;
            if (node != null && node.Level == 0)
            {
                group = node.Tag as Group;
                
                MOC.AddContact(user.InstanceID, s, group.Name);
                UpdateGroupsDGV(Cursor.Current);
            }
            else
            {
                MessageBox.Show(null, "A contact group must be selected", "Add user to Group", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        private void GroupsTV_DragOver(object sender, DragEventArgs e)
        {
            e.Effect = DragDropEffects.All;
        }

        private void GroupsTV_MouseUp(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                TreeNode n = GroupsTV.GetNodeAt(e.X, e.Y);
                if (n != null)
                {
                    
                    if (n.Level == 0)
                    {
                        deleteGroupToolStripMenuItem.Visible = true;
                        deleteContactToolStripMenuItem.Visible = false;
                    }
                    else
                    {
                        deleteGroupToolStripMenuItem.Visible = false;
                        deleteContactToolStripMenuItem.Visible = true;
                    }
                    if (n != null)
                    {
                        GroupsTV.SelectedNode = n;
                        if (n.Nodes.Count == 0)
                        {
                            GroupTV_CTX_Menu.Show(GroupsTV, GroupsTV.PointToClient(Cursor.Position));
                        }
                    }
                }

            }
        }

        private void AllOcsUsersDGV_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left && AllOcsUsersDGV.Rows.Count > 0)
            {
                AllOcsUsersDGV.Rows[e.RowIndex].Selected = true;
                User user = AllOcsUsersDGV.SelectedRows[0].DataBoundItem as User;
                String s = user.PrimaryURI;
                DoDragDrop(s, DragDropEffects.All);
            }
        }

        private void CollapsePBox_Click(object sender, EventArgs e)
        {
            GroupsTV.CollapseAll();
        }

        private void ExpandPBox_Click(object sender, EventArgs e)
        {
            GroupsTV.ExpandAll();
        }

        private void applyTemplateToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFileDialog OpenFile = new OpenFileDialog();

            OpenFile.AddExtension = true;
            OpenFile.DefaultExt = ".xml";
            OpenFile.CheckFileExists = false;
            OpenFile.Multiselect = false;
            OpenFile.Filter = "Xml Template File (*.xml)|*.xml|All files (*.*)|*.*";
            if (OpenFile.ShowDialog() == DialogResult.OK)
            {
                User user = SelectedUsersDGV.SelectedRows[0].DataBoundItem as User;
                Cursor SaveCursor = Cursor.Current;
                Cursor.Current = Cursors.WaitCursor;
                XmlTextReader xtr = new XmlTextReader(OpenFile.FileName);
                XmlDocument xd = new XmlDocument();
                xd.Load(xtr);
                XmlNode xnode = xd.DocumentElement;
                ReadNodes(xnode, user.InstanceID);
                xtr.Close();
                UpdateGroupsDGV(SaveCursor);
            }

        }

        private void UpdateGroupsDGV(Cursor SaveCursor)
        {
            Cursor.Current = Cursors.Hand;
            GroupsTV.Nodes.Clear();
            if (SelectedUsersDGV.Rows.Count > 0)
            {
                LoadGroupsAndContactsFromServer();
            }
            Cursor.Current = SaveCursor;
        }

        private void DonateLinkLabel_MouseClick(object sender, MouseEventArgs e)
        {
            System.Diagnostics.Process.Start("https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=W5UK4MXPMKL3N");
        }

        private void DonateLinkLabel_MouseMove(object sender, MouseEventArgs e)
        {
            Cursor.Current = Cursors.Hand;
        }

        private void deleteGroupToolStripMenuItem_Click(object sender, EventArgs e)
        {
            User u = SelectedUsersDGV.SelectedRows[0].DataBoundItem as User;
            Group r = GroupsTV.SelectedNode.Tag as Group;
            if (MessageBox.Show("Do you really want to delete group \"" + r.Name + "\" from " + u.DisplayName + " contacts?",
                            "Group Deletion",
                            MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                MOC.DeleteGroups(u.InstanceID,r.Name);
            }
                 

        }





    }
}
